/**
 * Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are NOT permitted except as agreed by
 * iAuto (Shanghai) Co., Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

import React, { useEffect, useState } from 'react';
import { Button, Input, Row, Col, Upload, message, Spin } from 'antd';
import { UploadProps } from 'antd/es/upload/interface';

import { customPreHandle } from '@/utils/soa/utils';

interface IUploadModal {
  onChange: (info: { fileName: string; fileUuid: string }) => void;
  value: string;
}

const UploadModal: React.FC<IUploadModal> = (props) => {
  const { onChange } = props;
  // 文件
  // eslint-disable-next-line
  const [fileName, setFileName] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (props.value) {
      setFileName(props.value);
    }
  }, [props.value]);

  const allowedFileTypes = ['image/jpeg', 'image/jpg', 'image/png', 'video/mp4', 'video/mov'];

  const uploadProps: UploadProps = {
    showUploadList: false,
    // accept:'video/mp4,video/avi,video/rmvb,video/wmv',
    // action: '/api/ms-soa-filestorage/v2/files',
    beforeUpload: (file) => {
      const isAllowedFileType = allowedFileTypes.includes(file.type);
      if (!isAllowedFileType) {
        message.error('你只能上传 JPEG、JPG、PNG、MP4、MOV 类型的文件!');
      }
      return isAllowedFileType;
    },
    customRequest: async (file) => {
      setLoading(true);
      customPreHandle(file, (info: any, r: any) => {
        setLoading(false);
        setFileName(info?.file?.name); // 设置文件名称
        onChange({
          fileName: info?.file?.name,
          fileUuid: r.uuid,
        });
        message.success('上传成功');
      });
    },
  };

  return (
    <Spin spinning={loading}>
      <Row>
        <Col flex={1}>
          <Upload className="upload" {...uploadProps}>
            <Input style={{ width: '100%' }} placeholder="请选择视频文件" value={fileName} />
          </Upload>
        </Col>
        <Col span={1}></Col>
        <Col>
          <Upload className="upload" {...uploadProps}>
            <Button type="primary" ghost>
              选择
            </Button>
          </Upload>
        </Col>
      </Row>
      <Row>
        <Col flex={1}>*支持格式：JPEG、JPG、PNG、MP4、MOV</Col>
      </Row>
    </Spin>
  );
};

export default UploadModal;
